package com.hunter.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Date;

/**
 * 2010-8-14 下午11:26:50 <br>
 * 日志处理工具类<br>
 * 目前包括处理以下类型日志:
 * <ul>
 * <li>创建索引的输出日志</li>
 * <li>异常信息的输出日志</li>
 * </ul>
 * 
 * @author mkk
 */
public class LogUtil {

	private static String format = "yyyyMMdd";
	private static FileChannel logChannel;
	private static FileChannel indexChannel;
	

	/**
	 * Get Log file channel
	 * @return
	 * @throws IOException
	 */
	private static FileChannel getLogFileChannel() throws  IOException {
		if(logChannel==null) {
			FileOutputStream fos=null;
			fos=new FileOutputStream(getSaveExceptionFile(),true);
			logChannel=fos.getChannel();
		}
		return logChannel;
	}
	
	/**
	 * Get Index file channel
	 * @return
	 * @throws IOException
	 */
	public static FileChannel getIndexFileChannel() throws  IOException {
		if(indexChannel==null) {
			FileOutputStream fos=null;
			fos=new FileOutputStream(getCreatIndexFile(),true);
			indexChannel=fos.getChannel();
		}
		return indexChannel;
	}

	/**
	 * 获取保存异常日志的文件<br>
	 * 根据日期来获取
	 * 
	 * @return
	 * @throws IOException
	 */
	public static File getSaveExceptionFile() throws IOException {
		File f = new File(PropertiesUtil.LOG_PATH + File.separator
				+ SystemUtil.formatDate(new Date(), format) + ".log");
		if (!f.exists()) {
			f.createNewFile();
		}
		return f;
	}

	/**
	 * 获取保存创建索引的日志文件<br>
	 * 根据日期来获取
	 * 
	 * @return
	 * @throws IOException
	 */
	public static File getCreatIndexFile() throws IOException {
		File f = new File(PropertiesUtil.LOG_PATH + File.separator
				+ SystemUtil.formatDate(new Date(), format) + "-index.log");
		if (!f.exists()) {
			f.createNewFile();
		}
		return f;
	}

	/**
	 * 保存异常日志信息
	 * 
	 * @param e 捕获的异常对象
	 */
	public static void saveExceptionLog(final Exception e) {
		if (e == null) {
			return;
		}
		new Thread() {
			public void run() {
				try {
					ByteBuffer buffer=ByteBuffer.wrap(e.getMessage().getBytes());
					getLogFileChannel().write(buffer);
				} catch (Exception ex) {
					System.out.println("Save exception log exception(LogUtil): "+e.getMessage());
				} 
			}
		}.start();
	}

}
